package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xrit.sunnyday.service.CheckItemService;
import com.xrit.sunnyday.dao.CheckItemMapper;
import com.xrit.sunnyday.common.MessageConstant;
import com.xrit.sunnyday.common.PageResult;
import com.xrit.sunnyday.common.QueryPageBean;
import com.xrit.sunnyday.pojo.CheckItem;
import com.xrit.sunnyday.common.SunnydayException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
@Service(interfaceClass = CheckItemService.class)
public class CheckItemServiceImpl implements CheckItemService {
    @Autowired
    private CheckItemMapper checkitemMapper;

    @Override
    public List<CheckItem> findAll() {
        return checkitemMapper.findAll();
    }

    @Override
    public PageResult findPageAll(QueryPageBean queryPageBean) {
        //判断是否有条件(Empty:空的)
        if(!StringUtils.isEmpty(queryPageBean.getQueryString())){
            //有就加上%
            //开启分页插件(参数是当前页,每页显示条数,查询条件)
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //调用查询方法
        List<CheckItem> checkItemList = checkitemMapper.findPageAll(queryPageBean.getQueryString());
        //new pageinfo(他能自动帮我们计算出需要分页信息)
        PageInfo pageInfo = new PageInfo<>(checkItemList);
        //拿到需要数据之后返回
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public void save(CheckItem checkItem) {
        checkitemMapper.save(checkItem);
    }


    @Override
    public void delete(Integer id) throws SunnydayException {
        //判断该检查项是否被检查组关联
        int count1 = checkitemMapper.findItMatterById(id);
        if(count1>0){
            //有就不删除,抛出自定义异常(要不要删看公司需求)
            throw new SunnydayException(MessageConstant.DELETE_CHECKITEM_ERROR);
        }
        //先判断该检查项是否存在
        int count2 = checkitemMapper.findIsById(id);
        if(count2>0){
            //count>0代表有就删除检查项
            checkitemMapper.delete(id);
        }
    }

    @Override
    public CheckItem findById(Integer id) {
        return checkitemMapper.findById(id);
    }

    @Override
    public void update(CheckItem checkItem) {
        checkitemMapper.update(checkItem);
    }
}
